iT邦幫忙

2023 iThome 鐵人賽

DAY 7
0
Software Development

Unity遊戲開發系列 第 7

DAY07 Unity基礎實作(1)

  • 分享至 

  • xImage
  •  

點選asset store可以從裡面下載免費資源來使用,在練習製作遊戲時會有很大的幫助
https://ithelp.ithome.com.tw/upload/images/20230922/20162530ZLobP7DEQn.png
也可以直接上網查詢Unity asset store來下載
https://assetstore.unity.com/zh


實作

先在Hierarchy欄位中建立一個2D Object裡的square方塊當作角色
https://ithelp.ithome.com.tw/upload/images/20230922/20162530VztuJIj3ao.png
點選方塊在Inspector中加入rigidbody2D和box collider2D
https://ithelp.ithome.com.tw/upload/images/20230922/20162530bncBkv7eKB.png
待更

結合移動和碰撞的基礎功能
程式碼

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
[RequireComponent(typeof(Rigidbody2D))]
public class playcontrol : MonoBehaviour
{
    Rigidbody2D rigid2D;
    [SerializeField]
    private float speed;
    [SerializeField]
    private float speed_x_constraint;
    public int hp = 20;
    public int jumpcheck=0;
 void Start()
    {
        rigid2D = this.gameObject.GetComponent<Rigidbody2D>();     
    }
     void Update()
    {
        float deltatime = Time.deltaTime;
        //跳躍
        if (Input.GetKeyDown(KeyCode.Space) && jumpcheck<2)
        {
            rigid2D.AddForce(new Vector2(0, 200), ForceMode2D.Impulse);
            jumpcheck +=1;
        }
        //右移動
         if (Input.GetKey(KeyCode.D))
        {
            rigid2D.velocity = new Vector2(speed_x_constraint, rigid2D.velocity.y);          
        }
         //左移動
         if(Input.GetKey(KeyCode.A))
        {
            rigid2D.velocity = new Vector2(-speed_x_constraint, rigid2D.velocity.y);          
        }     
    }
    void OnCollisionEnter2D(Collision2D coll) {
        if (coll.gameObject.tag == "trap") {
            hp -= 1;    
            rigid2D.AddForce(new Vector2(0, 100), ForceMode2D.Impulse);
         }
        if (coll.gameObject.tag == "Scenesobject") {
            jumpcheck = 0;
        }       
    }
  }

晚點整理完上圖


參考資料
https://www.youtube.com/watch?v=_LdnD8zN5OU


上一篇
DAY06 Unity 變數宣告和Inspector
下一篇
DAY08 Unity生成物件
系列文
Unity遊戲開發30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言